package com.reformer.commons.utils;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 绘图工具类
 *
 * @author sdc
 */
public class GraphicsUtil {
    /**
     * 绘图
     *
     * @param str       字符内容
     * @param os        输出流
     * @param width     图片宽度
     * @param height    图片高度
     * @param font      字体
     * @param backgroud 背景颜色
     * @param fontColor 字体颜色
     * @throws IOException
     */
    public static void draw(String str, OutputStream os, int width, int height, Font font, Color backgroud, Color fontColor) throws IOException {
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        // Font font = new Font("Times New Roman", Font.PLAIN, 20);
        Graphics2D g = image.createGraphics();
        g.setFont(font);
        // Color color = new Color(random.nextInt(255), random.nextInt(255),
        // random.nextInt(255));
        // g.setColor(new Color(random.nextInt(255), random.nextInt(255),
        // random.nextInt(255)));
        g.setBackground(backgroud);
        g.clearRect(0, 0, width, height);
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(str, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = y - ascent;
        char[] content = str.toCharArray();
        g.setFont(font);
        g.setColor(fontColor);
//		for (int i = 0; i < content.length; i++) {
//			String s = content[i] + "";
//			g.drawString(s, width / content.length * i + 3, height - 6);
//		}
        g.drawString(str, (int) x, (int) baseY);
        g.dispose();
//		ImageIO.write(image, "jpg", os);
        encoder.encode(image);
    }

    /**
     * 绘图
     *
     * @param str 字符内容
     * @param os  输出流
     * @throws IOException
     */
    public static void draw(String str, OutputStream os) throws IOException {
        draw(str, os, 150, 40, new Font("宋体", Font.PLAIN, 15), Color.WHITE, Color.RED);
    }

//    public static void main(String[] args) throws FileNotFoundException, IOException {
//        draw(new String("请完成上一次付款"), new FileOutputStream("/tempdemo.jpg"));
//    }
}
